package com.quectel.util.servlet;

import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.servlet.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * servlet请求帮助类
 *
 * @author CL
 * @email louis.cao@quectel.com
 * @date 2019-03-19 15:17:00
 */
public class ServletRequestUtils {

    /**
     * 得到所有的请求头
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllHeaders(HttpServletRequest request) {

        Map<String, String> headers = new HashMap<>();

        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                headers.put(headerName, request.getHeader(headerName));
            }
        }
        return headers;
    }

    /**
     * 得到真实的来访者ip
     *
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        // 阿里云lsb转发需要从remoteip请求头中获取
        String remoteIp = request.getHeader("remoteip");
        if (!NetUtil.isUnknown(remoteIp)) {
            return remoteIp;
        }

        return ServletUtil.getClientIP(request);
    }

    /**
     * 是否是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header) ? true : false;
    }

}
